package com.freud.logic.business.service;

import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.freud.framework.base.BaseService;
import com.freud.framework.util.DateUtil;
import com.freud.logic.business.bean.District;
import com.freud.logic.business.bean.Repository;
import com.freud.logic.business.mapper.RepositoryMapper;

@Service
@Transactional
public class RepositoryService extends BaseService {

	@Autowired
	private RepositoryMapper repositoryMapper;

	@Autowired
	private DistrictService districtService;

	public List<Repository> getAll(RowBounds rb) {
		final List<Repository> repositories = repositoryMapper
				.getAll(new RowBounds());
		for (final Repository repository : repositories) {
			this.convert(repository);
		}
		return repositories;
	}

	public Repository getById(int id) {
		return this.convert(repositoryMapper.get(id));
	}

	public void insert(Repository repository) {
		repository.setOperateDate(DateUtil.currentTimestamp());
		repositoryMapper.insert(repository);
	}

	public void update(Repository repository) {
		Repository exist = repositoryMapper.get(repository.getId());
		exist.setName(repository.getName());
		exist.setDistrictId(repository.getDistrictId());
		exist.setOperateDate(DateUtil.currentTimestamp());
		repositoryMapper.update(exist);
	}

	public void delete(int id) {
		repositoryMapper.delete(id);
	}

	private Repository convert(final Repository repository) {
		District district = districtService.getById(repository.getDistrictId());
		repository.setDistrict(district == null ? new District() : district);
		return repository;
	}

}
